/**
 * 收到请求时，把网页响应回去
http://localhost:8081/
将index.html响应到前端
*/

const fs =require("fs")
const http =require("http")
const url=require("url")
const path=require("path")
const https=require("https")
const cheerio = require("cheerio")

var reqUrl="https://maoyan.com/films"
var movieList=[];

http.createServer((req,res)=>{
    var urlObj=url.parse(req.url);
    var pathname=urlObj.pathname;
    if(pathname=='/'){
        //读网页文件用readFile,读取得是buffer数据
        var filePath=path.join(__dirname,"/index.html")
        fs.readFile(filePath,(err,data)=>{
           if(err){
               console.log(err)
           }else{
            res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
            res.write(data)
            res.end()
           }
        })
    }else if(pathname=="/getlist"){
        var htmlStr="";
        // resObj是一个可读流
        https.get("https://maoyan.com/films?showType=3",(resObj)=>{
            resObj.on("data",(chunk)=>{
                //chunk是一个buffer数据，+=后自动转换为字符串
                htmlStr+=chunk;
            })
            resObj.on("end",()=>{
                // console.log(htmlStr);//输出页面内容
                var $=cheerio.load(htmlStr)
                $(".movie-item-title a").each((i,el)=>{
                  var movieTitle=$(el).text();
                //   console.log(movieTitle)
                  var movieId=$(el).attr("data-val");
                  movieId=movieId.slice(movieId.indexOf(":")+1,-1)
                //   console.log(movieId)
                  var num1=$(el).parent().next().children(".integer").text();
                  var num2=$(el).parent().next().children(".fraction").text();
                  var movieScore=num1+num2;
                  if(movieScore==''){
                      movieScore="暂无评分"
                  }
                  var movieObj={movieId:movieId,movieTitle,movieTitle,movieScore:movieScore}
                  movieList.push(movieObj)
                })

                res.writeHead(200,{"Content-Type":"text/plain"});
                res.write(JSON.stringify(movieList));
                res.end()
            })
        })
    }
}).listen(8081)